package com.example.dao;

import com.example.domain.User;
import com.example.util.JDBCUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.EmptyStackException;
import java.util.List;

/**
 * 操作数据库中User表
 */
public class UserDao {

    //声明JdbcTemplate对象共用对数据库的操作
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    /**
     * 登陆方法
     *
     * @param loginUser 只有用户名和密码
     * @return user 包含用户全部信息，没有查询到，返回null值
     */
    public User login(User loginUser) {
        try {
            String sql = "select * from user where username=? and password=?";
            User user = template.queryForObject(sql,
                    new BeanPropertyRowMapper<User>(User.class),
                    loginUser.getUsername(), loginUser.getPassword());
            return user;
        } catch (EmptyResultDataAccessException e) {
            return null;
        }

    }

    /**
     * 注册方法
     */
    public int register(User user) {
        String sql = "insert into user(username,password,email,relname,phone,gender,birthday) value(?,?,?,?,?,?,?)";
        int update = template.update(sql,
                user.getUsername(),
                user.getPassword(),
                user.getEmail(),
                user.getRelname(),
                user.getPhone(),
                user.getGender(),
                user.getBirthday());
        return update;
    }

}
